package com.itheima.tilas.controller;

import com.itheima.tilas.Utils.ResultUtil;
import com.itheima.tilas.annotation.Log;
import com.itheima.tilas.dto.SelectClazzPageDTO;
import com.itheima.tilas.entity.Clazz;
import com.itheima.tilas.po.InsertClazzOneParam;
import com.itheima.tilas.po.SelectClazzPageParam;
import com.itheima.tilas.po.UpdateClazzParam;
import com.itheima.tilas.service.ClazzService;
import jakarta.annotation.Resource;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.ibatis.annotations.Delete;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Objects;

/**
 * 班级控制层
 *
 * @author 132
 */
@RestController
@RequestMapping("/clazzs")
@CrossOrigin
public class ClazzController {
    @Resource
    ClazzService clazzService;

    @GetMapping
    public ResultUtil selectClazzPage(SelectClazzPageParam param) {
        if (Objects.nonNull(param)) {
            return clazzService.selectClazzPage(param);
        } else {
            return ResultUtil.fail("本次查询失败");
        }
    }

    @DeleteMapping("/{id}")
    @Log
    public ResultUtil deleteClazzById(@PathVariable("id") Integer id) {
        if (Objects.nonNull(id)) {
            int flag = clazzService.deleteClazzById(id);
            return ResultUtil.success("删除成功,成功删除" + flag + "条数据");
        } else {
            return ResultUtil.fail("删除失败请检查参数");
        }
    }

    @PostMapping
    @Log
    public ResultUtil insertClazzOne(@RequestBody InsertClazzOneParam param) {
        int flag = clazzService.insertClazzOne(param);
        return flag > 0 ? ResultUtil.success("插入一条数据成功") : ResultUtil.fail("插入数据失败");
    }

    @GetMapping("/{id}")
    public ResultUtil selectClazzById(@PathVariable Integer id){
        SelectClazzPageDTO dto = clazzService.selectClazzById(id);
        if (Objects.nonNull(dto)){
            return ResultUtil.success("查询成功",dto);
        }else {
            return ResultUtil.success("查询失败");
        }
    }

    @PutMapping
    @Log
    public ResultUtil updateClazzById(@RequestBody UpdateClazzParam param){
        int flag = clazzService.updateClazzById(param);
        return flag>0? ResultUtil.success("修改成功") : ResultUtil.fail("修改失败");
    }

    @GetMapping("/list")
    public ResultUtil selectClazzAll(){
        List<Clazz> clazzList = clazzService.selectClazzAll();
        if (CollectionUtils.isNotEmpty(clazzList)){
            return ResultUtil.success("查询到"+clazzList.size()+"条信息",clazzList);
        }else {
            return ResultUtil.fail("查询失败");
        }
    }

}
